package com.hiv.common.service;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.CannedAccessControlList;
import com.aliyun.oss.model.ObjectMetadata;
import com.hiv.common.enums.ErrorCode;
import com.hiv.common.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * @author zhanghong
 */
@Slf4j
@Service
public class OssService {

    @Value("${aliyun.oss.file.OSS_Endpoint}")
    private String ossEndpoint;
    @Value("${aliyun.oss.file.ACCESS_KEY}")
    private String ossAccessKey;
    @Value("${aliyun.oss.file.SECRET_KEY}")
    private String ossSecretKey;
    @Value("${aliyun.oss.file.BUCKET_NAME}")
    private String ossBucketName;
    @Value("${aliyun.oss.file.DOMAIN}")
    private String ossDomain;
    @Value("${aliyun.oss.file.CND}")
    private String cdnDomain;

    /**
     * 上传文件
     *
     * @param file
     * @return
     * @throws NoSuchAlgorithmException
     * @throws IOException
     */
    public String uploadFile(MultipartFile file, String dir) {
        if (file != null && file.getSize() > 0 && !file.getOriginalFilename().isEmpty()) {
            String originalFilename = file.getOriginalFilename();
            try {
                String random = RandomStringUtils.random(10, false, true);
                String key = makeMd5(System.currentTimeMillis() + random + "_" + originalFilename.substring(0, originalFilename.lastIndexOf('.'))) + originalFilename.substring(originalFilename.lastIndexOf('.'));
                InputStream fileInput = file.getInputStream();
                OSSClient ossClient = new OSSClient(ossEndpoint, ossAccessKey, ossSecretKey);
                ObjectMetadata objectMetadata = new ObjectMetadata();
                objectMetadata.setObjectAcl(CannedAccessControlList.PublicRead);
                ossClient.putObject(ossBucketName, dir +"/"+ key, fileInput, objectMetadata);
                ossClient.shutdown();
                return String.format("https://%s/%s", cdnDomain, dir +"/"+ key);
            } catch (Exception ex) {
                log.error("上传文件失败", ex.getMessage(), ex);
                throw new BusinessException(ErrorCode.ERR_UPLOAD_FILE);
            }
        }
        return "";
    }

    private String makeMd5(String string) throws NoSuchAlgorithmException {
        MessageDigest messageDigest = MessageDigest.getInstance("MD5");
        try {
            messageDigest.update(string.getBytes("utf-8"));
        } catch (UnsupportedEncodingException e) {
            log.error("MD5 Format Error", e);
        }
        return new BigInteger(1, messageDigest.digest()).toString(16);
    }

}
